<template>
    <div id="app">
        <router-view />
        <Play :percent="percent" @slide="slide" @LastNext="normalPlay_T" />
        <SmallPlay :percent="percent" @LastNext="normalPlay_T" />
        <!-- 音频 -->
        <audio
            :src="url"
            ref="audio"
            @canplay="audioCanPlay"
            @ended="audioEnded"
            @timeupdate="audioTimeUpdate"
        >
            {{ playTf }}
        </audio>
    </div>
</template>

<script>
import { mapState, mapMutations, mapGetters, mapActions, createNamespacedHelpers } from 'vuex';
const {
    mapState: controlAudioMapState,
    mapMutations: controlAudioMapMutations,
    mapGetters: controlAudioMapGetters,
    mapActions: controlAudioMapActions
} = createNamespacedHelpers('controlAudio');

import Play from './components/Play.vue';
import SmallPlay from './components/SmallPlay.vue';
import { Toast } from 'vant';
export default {
    name: 'App',
    components: { Play, SmallPlay },
    data() {
        return {
            // 音频标签的DOM
            audio: null,
            // 音频总时长
            duration: 0,
            // 当前播放时间和音频总时间的百分比
            percent: 0,

            // 歌词
            Lyric: [],
            //显示歌词时间的区间
            startTime: 0,
            //开始查找歌词位置
            lyricIndex: 0,

            normalPlay: false,
        }
    },
    //属性计算
    computed: {
        ...controlAudioMapState(['playSuspend', 'url', 'id', 'obtainNewData_YN', 'vuexInit', 'songsData', 'pattern', 'songIndex']),



        // 监听 音频播放状态 的切换
        playTf() {
            if (this.audio) { this.playPauseFn(this.playSuspend); }
            return this.playSuspend;
        },
    },
    //方法 
    methods: {
        ...controlAudioMapMutations([
            'changeAudioUrl',
            'playSuspend_Switch',
            'changeAudio_Cover_SongTitle_Singer',
            'changeStateProperty',
            'addSongsData',
            'SelectPlay',
        ]),


        // 请求获取 封面 歌名 歌手名 
        getCover_SongTitle_Singer(ids) {
            this.axios({
                method: "GET",
                url: "/song/detail",
                params: { ids }
            }).then((result) => {
                console.log("🚀 ==> get ==> result", result);
                if (result.data.code === 200) {

                    // 歌手名 合体
                    let singer = '';
                    result.data.songs[0].ar.forEach((v) => {
                        singer += v.name + ' / '
                    });
                    singer = singer.slice(0, -3);

                    // 传递数据
                    let data = {
                        cover: result.data.songs[0].al.picUrl+ '?param=140y140',
                        songTitle: result.data.songs[0].name,
                        singer,
                    };
                    // 改变显示数据
                    this.changeAudio_Cover_SongTitle_Singer(data);


                    // 请求歌词， 并传 要存储的参数
                    this.getLyric(this.url, ids, data.cover, data.songTitle, data.singer);
                }
            }).catch((err) => {
                console.log("🚀 ==> get ==> err", err);
            });
        },

        // 请求获取 歌词
        getLyric(url, id, cover, songTitle, singer) {
            this.axios({
                method: "GET",
                url: "/lyric",
                params: { id }
            }).then((result) => {
                // console.log("🚀 ==> getLyric ==> result", result);
                if (result.data.code === 200) {


                    //解析歌词
                    let lyricData = result.data.lrc.lyric.split(/\n/);
                    console.log('lyricData ==> ', lyricData);

                    // 时间提示正则
                    let lyricReg = /^\[\d{2}:\d{2}\.\d{2,3}\].*$/;

                    //data临时存储变量 //lyricYesNo 是否没有时间提示
                    let data = [];
                    let lyricYesNo = null;
                    lyricData.forEach((v, i) => {

                        // 判断是否 有时间提示
                        if (lyricReg.test(v)) {
                            // 执行一次 没有时间提示 赋值
                            if (i < 1) { lyricYesNo = false; }


                            //按照 ]切割
                            let ly = v.split(/\]/);
                            // console.log("🚀 ==> getLyric ==> ly", ly);
                            ly[0] = ly[0].slice(1);
                            // console.log("🚀 ==> getLyric ==> ly[0]", ly[0]);

                            // 判断 数组元素是否为空
                            if (ly[1]) {
                                ly[1] = ly[1].trim();
                                //处理ly[0], 转换为秒
                                //按照 : 进行切割, 分成 分钟 和 秒
                                let time = ly[0].split(/:/);
                                // console.log('time ==> ', time);

                                let minutes = Number(time[0]);
                                let seconds = Number(time[1]);
                                // console.log('minutes ==> ', minutes);
                                // console.log('seconds ==> ', seconds);

                                let t = (minutes * 60 + seconds).toFixed(2);
                                // 添加数组元素 
                                data.push({ time: Number(t), text: ly[1] });
                            }
                        }
                        // 没有时间提示直接 
                        else {
                            // 执行一次 没有时间提示 赋值
                            if (i < 1) { lyricYesNo = true; }

                            // 判断 数组元素不为空，直接添加数组元素 
                            if (v) { data.push({ text: v }); }
                        }
                    });

                    // 传递数据
                    this.changeStateProperty({ key: 'lyricYesNo', value: lyricYesNo });
                    this.changeStateProperty({ key: 'lyric', value: data });
                    this.Lyric = data;
                    console.log("🚀 ==> getLyric ==> data", data);


                    // 新数据 内容添加
                    let obj = {
                        url,
                        id,
                        cover,
                        songTitle,
                        singer,
                        lyric: data,
                        lyricYesNo: lyricYesNo,
                    };

                    this.addSongsData(obj);
                    sessionStorage.setItem(
                        "songsData",
                        JSON.stringify(this.songsData)
                    );

                    //重置查找歌词
                    this.startTime = 0;
                    this.lyricIndex = 0;
                }

            }).catch((err) => {
                console.log("🚀 ==> getLyric ==> err", err);
            });
        },

        // 播放暂停
        playPauseFn(tf) {
            if (tf) {
                this.audio.play();
                this.changeStateProperty({ key: "playSuspend", value: true });
            }
            else {
                this.audio.pause();
                this.changeStateProperty({ key: "playSuspend", value: false });
            }
        },


        // 调整正常播放
        normalPlay_T() { this.normalPlay = true; },

        //监听音频 加载完成事件(可以播放时)
        audioCanPlay() {
            console.log('音频可以播放了');
            console.log("🚀 ==> audioCanPlay ==> this.normalPlay", this.normalPlay);
            if (!this.vuexInit) {
                this.playPauseFn(true);
            }
            if (this.normalPlay) {
                this.playPauseFn(true);
                this.normalPlay = false;
            }


            // 获取新数据
            if (this.obtainNewData_YN) {
                // 请求新数据 + 内容添加
                this.getCover_SongTitle_Singer(this.id);
                // 新数据获取完毕
                console.log("新数据获取完毕");
                // 关闭新数据获取模式
                this.changeStateProperty({ key: 'obtainNewData_YN', value: false });
            }

            // 获取音频总时长
            this.duration = this.audio.duration;
            // console.log("🚀 ==>  this.audio.duration ==> 音频总时长", this.audio.duration);
            //换算分钟
            let minutes = Math.floor(this.duration / 60);
            minutes = minutes >= 10 ? minutes : '0' + minutes;
            //换算秒钟
            let seconds = Math.floor(this.duration % 60);
            seconds = seconds >= 10 ? seconds : '0' + seconds;
            // 合成文本
            let durationText = `${minutes}:${seconds}`;
            // 修改 总时长显示文本
            this.changeStateProperty({ key: 'durationText', value: durationText });
        },


        //监听音频播放进度变化
        audioTimeUpdate() {

            //获取音频的当前播放时间
            let currentTime = this.audio.currentTime;
            // console.log('currentTime ==> ', currentTime);
            //获取分钟
            let minutes = Math.floor(currentTime / 60);
            minutes = minutes >= 10 ? minutes : '0' + minutes;
            //获取秒钟
            let seconds = Math.floor(currentTime % 60);
            seconds = seconds >= 10 ? seconds : '0' + seconds;
            // 合成文本
            let currentTimeText = `${minutes}:${seconds}`;
            // 修改 当前时间显示文本
            this.changeStateProperty({ key: 'currentTimeText', value: currentTimeText });

            //修改 当前播放时间和音频总时间的百分比
            this.percent = currentTime / this.duration;
            // console.log("🚀 ==> audioTimeUpdate ==>  this.percent ", this.percent);




            if (this.Lyric) {
                // console.log("🚀 ==> audioTimeUpdate ==> this.Lyric", this.Lyric);

                for (let i = 0; i < this.Lyric.length; i++) {
                    // console.log("🚀 ==> audioTimeUpdate ==> Lyric", this.Lyric);
                    // console.log("this.startTime ===> ", this.startTime);
                    // console.log("currentTime====> ", currentTime);
                    if (this.Lyric[i].time > this.startTime && this.Lyric[i].time <= currentTime) {
                        // console.log('进来了');
                        //出现当前播放时间的弹幕内容
                        // console.log(this.Lyric[i]);
                        this.lyricIndex = i;

                        this.changeStateProperty({ key: 'lyric_Index', value: this.lyricIndex });
                    }
                }
                // console.log('lyricIndex ==> ', this.lyricIndex);
            }
            this.startTime = currentTime;
        },

        //监听音频是否播放结束
        audioEnded() {
            console.log("音频播放结束, 可以根据播放模式进行播放下一首");
            this.normalPlay = true;

            //顺序播放
            if (this.pattern === 0) {

                let index = this.songIndex + 1;

                if (index === this.songsData.length) { index = 0; }
                console.log("🚀 ==> audioEnded ==> index", index);
                this.SelectPlay(index);
            }
            //随机播放
            else if (this.pattern === 1) {
                let index = this.randomIndex(this.songIndex);
                this.SelectPlay(index);
            }
            //单曲循环
            else if (this.pattern === 2) {
                this.audio.src = this.url;
            }
        },

        // 获取一个随机下标
        randomIndex(index) {
            // 生成一个随机数
            let num = Math.floor(Math.random() * this.songsData.length);

            // 与当前播放下标 相同就进行递归
            if (num === index) { return this.randomIndex(index); }
            else { return num };
        },

        // 改变当前播放时间
        slide(v) {
            this.percent = v.value / 100;
            this.audio.currentTime = this.duration * this.percent;
        },
    },

    created() {
        this.$nextTick(() => {
            //获取音频节点 
            this.audio = this.$refs.audio;
            // console.log(this.audio);
        });

        //获取会话默认歌曲列表数据
        let appSongsData = sessionStorage.getItem("songsData");
        // console.log("appSongsData ==> ", appSongsData);
        if (appSongsData) {
            appSongsData = JSON.parse(appSongsData);
            this.changeStateProperty({
                key: "songsData",
                value: appSongsData,
            });
        }
    },
}

</script>
<style lang="less">
@import './assets/chong1zhi2mo3ren.css';
@import './assets/chong1zhi2chang3yong4yuan5su.css';

audio {
    height: 50px;
}
</style>
